from django.middleware.common import MiddlewareMixin
from django.http.response import HttpResponse,JsonResponse
import django_redis
from . import const
import pickle
from . import  models
import time

class TokenMiddleWare(MiddlewareMixin):
    url_white_list = [
        'login', 'register'
    ]
    #/login
    def check_url(self,path_info): #检查url是否在白名单
        for url in const.url_white_list:
            if url in path_info:
                return True

    def process_request(self,request):
        if not self.check_url(request.path_info): #如果不在白名单，校验token
            token = request.COOKIES.get("token")
            r = django_redis.get_redis_connection()

            if not token:
                ret = {"code": 36, "msg": 'not login'}
                return JsonResponse(ret)

            user = r.get(const.login_key_prefix+token)
            # request.user = user
            request.user = pickle.loads(user)
            if not user:
                ret = {"code":36,"msg":'not login'}
                return JsonResponse(ret)


    def process_response(self,request,response):
        print("process_reponse")
        print(request)
        print(response)
        return response

    def process_exception(self,request,exception):
        print("process_exception")
        print(request)
        print(exception)
        return HttpResponse("系统异常，请联系管理员")

class FuncCountMiddleWare(MiddlewareMixin):
    def process_request(self,request,response):
        url=request.path_info
        today=time.strftime("%Y-%m-%d")
        today_data=models.FunCount.objects.filter(url=url,date=today).first()
        if today_data:
            today_data.count+=1
            today_data.save()
        else:
            models.FunCount.objects.create(url=url,count=1)
        return response